package com.nantai.jiafang.nantaijiafang.zhijian.fragment;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;

import com.blankj.utilcode.util.StringUtils;
import com.nantai.jiafang.nantaijiafang.Data;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.ViewModel.Zhijian_Net;
import com.nantai.jiafang.nantaijiafang.activity.adapter.ProductSpinnerAdapter;
import com.nantai.jiafang.nantaijiafang.base.BaseFragment;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.ColourInfo;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.GroupInfo;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.Item.HeardItem_1;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.ProductInfo;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.SewingDetail;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.StaffInfo;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.Tip;
import com.nantai.jiafang.nantaijiafang.databinding.ActiivitySewingAddBinding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.android.volley.VolleyLog.TAG;

public class SewingAddFragment extends BaseFragment<ActiivitySewingAddBinding> implements View.OnClickListener {

    private ActiivitySewingAddBinding binding;

    private ProductSpinnerAdapter productSpinnerAdapter;


    private  Calendar calendar = Calendar.getInstance();

    private String guid="",id="",cInvCode,cInvName,Color;

    private HeardItem_1 heardItem_1=null;


    public static SewingAddFragment initSewingAddFragment(HeardItem_1 heardItem_1){
        SewingAddFragment sewingAddFragment = new SewingAddFragment();
        sewingAddFragment.setHeardItem_1(heardItem_1);
        return sewingAddFragment;
    }
    private void setHeardItem_1(HeardItem_1 heardItem_1){
        this.heardItem_1=heardItem_1;
    }

    @Override
    public int setlayoutid() {
        return R.layout.actiivity_sewing_add;
    }

    @Override
    public void initUI(ActiivitySewingAddBinding binding) {
        EventBus.getDefault().register(this);
        this.binding = binding;
        this.binding.setOnclickListener(this);
//        使用bundle时跳转奔溃未找到原因
//        Bundle bundle = this.getArguments();
//            SewingDetail detail = (SewingDetail)bundle.getSerializable("detail");

        Intent intent = new Intent();
        SewingDetail detail = (SewingDetail) intent.getSerializableExtra("detail");

            if (detail != null) {
                initValues(detail);
            }

        getData();
        initView();
    }

    private void initValues(SewingDetail detail){
        guid = detail.getGuid();
        id = detail.getID();
        binding.defectNum.setText(detail.getDefectNum());
        binding.defectDes.setText(detail.getDefectDes());
        binding.inspectTime.setText(detail.getInspectTime());
//        binding.checkRateHF.setText(detail.getCheckRate_HF());
//        binding.comNum.setText(detail.getComNum());
        binding.facArea.setText(detail.getFacArea());
        binding.packQty.setText(detail.getPackQty());
        binding.inspectorName.setText(detail.getInspectorName());
        cInvCode = detail.getcInvCode();
        cInvName = detail.getcInvName();
        Color = detail.getColourName();

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_back:
                getFragmentManager().popBackStack();
                break;
            case R.id.btn_defects:
                if(!StringUtils.isEmpty(binding.defectNum.getText())){
                    EventBus.getDefault().postSticky(Integer.valueOf(binding.defectNum.getText().toString()));
                }
//
                if(!StringUtils.isEmpty(binding.defectDes.getText())){
                    EventBus.getDefault().postSticky(binding.defectDes.getText().toString());
                }
                getActivity().getSupportFragmentManager().beginTransaction()
                        .addToBackStack(null)
                        .setCustomAnimations(R.anim.in_from_left,R.anim.in_from_right,R.anim.out_from_left,R.anim.out_from_right)
                        .add(R.id.container4,new SewingDefectsFragment())
                        .commit();
                break;
            case R.id.inspectTime:
                DatePickerDialog dpd2 = new DatePickerDialog(getContext(), Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd2.show();
                break;

            case R.id.btn_save:
                saveData();
                break;
        }
    }

    private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            String month="";
            String day="";
            if (monthOfYear<9){
                month="0"+(monthOfYear+1);
            }else {
                month=""+(monthOfYear+1);
            }
            if (dayOfMonth<10){
                day="0"+dayOfMonth;
            }else {
                day=""+dayOfMonth;
            }
            binding.inspectTime.setText(myyear + "-" +month + "-" + day);
        }
    };

    private void initView(){

        binding.cInvNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ProductInfo info = (ProductInfo)parent.getItemAtPosition(position);
                cInvCode = info.getcInvCode();
                cInvName = info.getcInvName();

                Log.e(TAG, "onItemSelected: "+binding.groupSpinner.getItemIdAtPosition(position) );
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        binding.groupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                GroupInfo info = (GroupInfo)parent.getSelectedItem();
                getAllGroupInfo(info.getcDepCode());
                Log.e(TAG, "onItemSelected: "+binding.groupSpinner.getSelectedItem() );
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        binding.colorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ColourInfo info = (ColourInfo)parent.getSelectedItem();
                Color = info.getColorName();
                Log.e(TAG, "onItemSelected: "+binding.colorSpinner.getSelectedItem() );
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    private void getData(){

        getCInvNameList();

        getAllGroupInfo();

        getAllColorByPro();

    }

    private void getAllGroupInfo(){
        Zhijian_Net.getAllGroupInfo(this.getContext(), new Zhijian_Net.GetSingData<List<GroupInfo>>() {
            @Override
            public void success(List<GroupInfo> s) {
                ArrayAdapter<GroupInfo> arrayAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_spinner_item,s);
                arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                binding.groupSpinner.setAdapter(arrayAdapter);

            }
        });
    }

    private void getAllColorByPro(){
        Zhijian_Net.getAllColorByPro(this.getContext(),new Zhijian_Net.GetSingData<List<ColourInfo>>(){
            @Override
                public void success(List<ColourInfo> s){
                ArrayAdapter<ColourInfo> arrayAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_spinner_item,s);
                arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                binding.colorSpinner.setAdapter(arrayAdapter);

            }
        });
    }


    private void getAllGroupInfo(String groupCode){
        Map<String,String> map = new HashMap<>();
        map.put("GroupCode",groupCode);
        Zhijian_Net.getProducerByGroup(this.getContext(), map,new Zhijian_Net.GetSingData<List<StaffInfo>>() {
            @Override
            public void success(List<StaffInfo> s) {
                ArrayAdapter<StaffInfo> arrayAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_spinner_item,s);
                arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                binding.colorSpinner.setAdapter(arrayAdapter);
            }
        });
    }



    private void getCInvNameList(){
        Zhijian_Net.getProductInfo(this.getContext(), new Zhijian_Net.GetSingData<List<ProductInfo>>() {
            @Override
            public void success(List<ProductInfo> s) {

                productSpinnerAdapter = new ProductSpinnerAdapter(getContext(),R.layout.product_spinner,s);

                int position = -1;
                if(!StringUtils.isEmpty(cInvCode)){
                    for(int i = 0;i<s.size();i++){
                        if(s.get(i).getcInvCode().equals(cInvCode)){
                            position = i+1;
                            break;
                        }
                    }
                }

                binding.cInvNameSpinner.setAdapter(productSpinnerAdapter);

                if(position > 0){
                    binding.cInvNameSpinner.setSelection(position,true);
                    productSpinnerAdapter.notifyDataSetChanged();
                }



            }
        });
    }


    private void saveData(){
        GroupInfo groupInfo = (GroupInfo)binding.groupSpinner.getSelectedItem();
        StaffInfo staffInfo = (StaffInfo)binding.colorSpinner.getSelectedItem();
        Map<String,String> maps=new HashMap<>();
        maps.put("opType","saveQuiltHead");
        maps.put("Guid",guid);
        maps.put("ID",id);
        maps.put("cInvCode",cInvCode);
        maps.put("cInvName",cInvName);

        maps.put("PackQty",binding.packQty.getText().toString());
//        maps.put("ComNum",binding.comNum.getText().toString());
//        maps.put("CheckRate_HF",binding.checkRateHF.getText().toString());
        maps.put("GroupCode",groupInfo.getcDepCode());
        maps.put("GroupName",groupInfo.getcDepName());

//        maps.put("ProductCode",staffInfo.getStaffNumber());
//        maps.put("ProductorName",staffInfo.getStaffName());
//        maps.put("InspectorCode",binding..getText().toString());
        maps.put("InspectorName", Data.ZHIJIAN_Account);
        maps.put("InspectTime",binding.inspectTime.getText().toString());

        maps.put("FacArea",binding.facArea.getText().toString());
        maps.put("DefectNum",binding.defectNum.getText().toString());
        maps.put("DefectDes",binding.defectDes.getText().toString());
//        maps.put("UserName",binding.detailBatchNumber.getText().toString());

//        for (Iterator<Map.Entry<String, String>> it = maps.entrySet().iterator(); it.hasNext();){
//            Map.Entry<String, String> item = it.next();
//
//            if(StringUtils.isEmpty(item.getValue())){
//                it.remove();
//            }
//
//        }
        Zhijian_Net.saveEInspectHead(getContext(), maps, new Zhijian_Net.GetSingData<List<Tip>>() {
            @Override
            public void success(List<Tip> s) {
                Log.e(TAG, "success: "+s.get(0).getTip() );
                toast(s.get(0).getTip());
                getFragmentManager().popBackStack();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void setHid(String hid){
//        this.hid=hid;
        EventBus.getDefault().unregister(this);
    }

    public void setdefectDes(String context){
        binding.defectDes.setText(context);
    }

    public void setADefectNo(String count){
        binding.defectNum.setText(count);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}

